﻿using System;
using Elastic_EF.Models;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;

namespace Elastic_EF.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class LogController : ControllerBase
    {
        private readonly EFCoreContext _efContext;

        public LogController(EFCoreContext efContext)
        {
            _efContext = efContext;
        }

        [HttpGet("All")]
        public void MoreSql()
        {
            var log = new OperateLog()
            {
                Id = new Random().Next(500,2000),
                OperateType = new Random().Next(1,5),
                Creator = "Simon",
                CreatorId = 35742,
                CreateTime = DateTime.Now,
                Remark = "新增支付类型"
            };

            _efContext.OperateLog.Add(log);
            _efContext.SaveChanges();

            _efContext.OperateLog.FirstOrDefault(x => x.Id == log.Id);
            _efContext.OperateLog.FirstOrDefault(x => x.Remark == "新增支付类型");

            log.Remark = "新增支付类型";
            _efContext.SaveChanges();

            //删除，数据库无任何记录
            _efContext.OperateLog.Remove(log);
            _efContext.SaveChanges();
        } 

        [HttpGet("Create")]
        public void Create()
        {
            var log = new OperateLog()
            {
                Id = 1,
                OperateType = 2,
                Creator = "Simon",
                CreatorId = 35742,
                CreateTime = System.DateTime.Now,
                Remark = "新增支付类型"
            };

            _efContext.OperateLog.Add(log);

            _efContext.SaveChanges();
        }

        [HttpGet]
        [Route("GetById")]
        public OperateLog GetById(long id)
        {
            return _efContext.OperateLog.FirstOrDefault(x => x.Id == id);
        }

        [HttpGet("List")]
        public List<OperateLog> FindList(string name)
        {
            return _efContext.OperateLog.Where(x => x.Remark.Contains(name)).ToList();
        }

        [HttpPost("Delete")]
        public bool DeleteItem(long id)
        {
            var obj = _efContext.OperateLog.FirstOrDefault(x => x.Id == id);

            _efContext.OperateLog.Remove(obj);

            return _efContext.SaveChanges() > 0;
        }
    }
}